﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DNADataHiding.Model.Shared;

namespace DNADataHiding.Model
{
    public class DNASequence
    {
        private static Random rnd;

        static DNASequence()
        {
            rnd = new Random();
        }

        private string _sequence;
        private BinaryCodingRule _codingRule;

        public DNASequence(string sequence)
        {
            _sequence = sequence;
            _codingRule = new BinaryCodingRule();
        }

        public string ToBinary()
        {
            StringBuilder builder = new StringBuilder();

            foreach (var nucleotide in _sequence)
            {
                builder.Append(_codingRule.ToBinary(nucleotide));
            }

            return builder.ToString();
        }

        public override string ToString()
        {
            return _sequence;
        }

        public static DNASequence FromBinary(string binarySequence)
        {
            StringBuilder builder = new StringBuilder();
            BinaryCodingRule codingRule = new BinaryCodingRule();

            for (int i = 0; i < binarySequence.Count(); i = i+2)
            {
                builder.Append(codingRule.FromBinary(binarySequence.Substring(i, 2)));
            }

            return new DNASequence(builder.ToString());
        }

        
        public static DNASequence GetRandomSequence(int length)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                int randomVal = rnd.Next(1, 5);

                if (randomVal.Equals(1))
                    sb.Append("A");
                else if (randomVal.Equals(2))
                    sb.Append("C");
                else if (randomVal.Equals(3))
                    sb.Append("G");
                else if (randomVal.Equals(4))
                    sb.Append("T");
            }

            return new DNASequence(sb.ToString());
        }
        

        public bool IsPrefixOf(DNASequence sequence)
        {
            return sequence._sequence.StartsWith(this._sequence);
        }

        public int Length() 
        {
            return _sequence.Length;
        }

        public char GetNucleotideAt(int index)
        {
            return _sequence.ElementAt(index);
        }
            

        /*
        public IList<string> Split (int size)
        {
            IList<string> retValue = new List<string>();

            string binarySequence = this.ToBinary();

            for (int index = 0; index < binarySequence.Length; index += size)
            {
                retValue.Add(binarySequence.Substring(index, Math.Min(size, binarySequence.Length - index)));
            }

            return retValue;
        }
        */
    }
}
